package com.mgvlife.ddlw.util;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionContext;

public class HttpSessionUtil {
	public static final String admin_id = "admin_id";
	public static final String admin_name = "admin_name";
	public static final String superadmin_id = "superadmin_id";
	public static final String superadmin_name = "superadmin_name";

	public static Object getObject(String key) {
		Map<String, Object> m = ActionContext.getContext().getSession();
		return m.get(key);
	}

	public static String getString(String key) {
		Map<String, Object> m = ActionContext.getContext().getSession();
		return (String) m.get(key);
	}
	
	// 普通管理员
	public static void putAdmin(String id, String name) throws UnsupportedEncodingException {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put(admin_id, id);
		session.put(admin_name, name);
		// 写入Cookie
		HttpServletResponse response = ServletActionContext.getResponse();
		Cookie cookie = new Cookie("mgvlife_adminname", URLEncoder.encode(name,"utf-8"));
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	public static String getAdminStatus() {
		Map<String, Object> map = ActionContext.getContext().getSession();
		return (String)map.get(admin_id);
	}
	
	public static void removeAdmin() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.remove(admin_id);
		session.remove(admin_name);
		// 写入Cookie
		HttpServletResponse response = ServletActionContext.getResponse();
		Cookie cookie = new Cookie("mgvlife_adminname", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	// 超级管理员
	public static void putSuperAdmin(String id, String name) throws UnsupportedEncodingException {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put(superadmin_id, id);
		session.put(superadmin_name, name);
		// 写入Cookie
		HttpServletResponse response = ServletActionContext.getResponse();
		Cookie cookie = new Cookie("mgvlife_superadminname", URLEncoder.encode(name,"utf-8"));
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	public static String getSuperAdminStatus() {
		Map<String, Object> map = ActionContext.getContext().getSession();
		return (String)map.get(superadmin_id);
	}
	
	public static void removeSuperAdmin() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.remove(superadmin_id);
		session.remove(superadmin_name);
		// 写入Cookie
		HttpServletResponse response = ServletActionContext.getResponse();
		Cookie cookie = new Cookie("mgvlife_superadminname", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

}
